package utils

import (
	"errors"
	"github.com/Sir-yuChen/funAnalyse/global"
	"gorm.io/gorm"
)

type DBColumns struct {
	TableSchema            string `gorm:"column:TABLE_SCHEMA" json:"tableSchema"`
	TableName              string `gorm:"column:TABLE_NAME" json:"tableName"`
	ColumnName             string `gorm:"column:COLUMN_NAME" json:"columnName"`
	ColumnDefault          string `gorm:"column:COLUMN_DEFAULT" json:"columnDefault"`
	IsNullable             string `gorm:"column:IS_NULLABLE" json:"isNullable"`
	DataType               string `gorm:"column:DATA_TYPE" json:"dataType"`
	CharacterMaximumLength string `gorm:"column:CHARACTER_MAXIMUM_LENGTH" json:"characterMaximumLength"`
	CharacterSetName       string `gorm:"column:CHARACTER_SET_NAME" json:"characterSetName"`
	ColumnType             string `gorm:"column:COLUMN_TYPE" json:"columnType"`
	ColumnKey              string `gorm:"column:COLUMN_KEY" json:"columnKey"`
	Extra                  string `gorm:"column:EXTRA" json:"extra"`
	ColumnComment          string `gorm:"column:COLUMN_COMMENT" json:"columnComment"`
}

func NewDBColumns() *DBColumns {
	return &DBColumns{}
}

// GetDBColumns 表信息
func (d *DBColumns) GetDBColumns() ([]*DBColumns, error) {
	var doc []*DBColumns
	DB := new(gorm.DB)
	if d.TableName == "" {
		global.GVA_LOG.Error("table name cannot be empty")
		return nil, errors.New("table name cannot be empty！")
	}
	if global.GVA_CONFIG.System.DbType == "mysql" {
		DB = global.GVA_DB.Table("information_schema.columns").Where("table_schema= ? ", global.GVA_CONFIG.Mysql.Dbname).Where("TABLE_NAME = ?", d.TableName).Order("ORDINAL_POSITION asc")
	} else {
		global.GVA_LOG.Error("获取表信息 目前只支持mysql数据库")
		return nil, errors.New("获取表信息 目前只支持mysql数据库")
	}
	if err := DB.Find(&doc).Error; err != nil {
		return doc, err
	}
	return doc, nil
}

// GetTables 获取数据库的所有表名
func (d *DBColumns) GetTables(dbName string) (data []*TableName, err error) {
	var entities []*TableName
	sql := `select table_name as table_name from information_schema.tables where table_schema = ?`
	err = global.GVA_DB.Raw(sql, dbName).Scan(&entities).Error
	return entities, err
}
